﻿using MicroMq.Helper;
using MicroMq.Models;

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace MicroMq.Services
{
    /// <summary>
    /// 订阅器
    /// </summary>
    class SubscribeService : IHandlerService
    {
        private readonly EventWorkService eventWorkService;
        public SubscribeService(EventWorkService eventWorkService)
        {
            this.eventWorkService = eventWorkService;
        }

        byte IHandlerService.HandleType => (byte)HandleType.Subscribe;


        public void Hanlder(PeerConnection connection, ByteReadBuffer buffer)
        {
            var arr = Encoding.UTF8.GetString(buffer.ReadEnd()).Split("\n", StringSplitOptions.RemoveEmptyEntries);
            Subscribe(connection, arr[0], arr[1]);
        }

        void Subscribe(PeerConnection connection, string topicId, string groupId)
        {
            connection.AddGroup(topicId, groupId);
            Task.Factory.StartNew(() => eventWorkService.Emit(topicId, connection.peerStream));
        }
    }
}
